#!/usr/bin/python
# -*- coding: cp1250 -*-

from datetime import date
import re
import string
import time
import decimal
import calendar
import datetime

D = decimal.Decimal

zf = lambda x_s, y_n : string.zfill(str(x_s), y_n)
yyyymmdd_hhmmss = lambda : re.sub('[-:]','', re.sub(' ','_', time.strftime ("%Y-%m-%d %H:%M:%S", time.localtime())))
DDMMYYYYdot_YYYYMMDD = lambda x: "%s-%s-%s" % (x[-4:], x[3:5], x[:2])
dtnow = lambda : re.sub('[-:]','', re.sub(' ','T', time.strftime ("%Y-%m-%d %H:%M:%S", time.localtime())))

def hhmmss_sec(t):
    ''' convert time to seconds
        hh:mm:ss -> (hh*60*60)+(mm*60)+ss
    '''
    r = (int(t[:2])*60*60) # hh
    r += (int(t[3:5])*60) # mm
    r += int(t[6:]) # ss
    return r

if 0:
    print hhmmss_sec('00:02:20'), 140
    print hhmmss_sec('00:02:00'), 120
    print hhmmss_sec('00:01:20'), 80
    print hhmmss_sec('00:10:20'), 620
    print hhmmss_sec('00:30:00'), 1800

def getTimeIsoGmt():
    return time.strftime ("%Y-%m-%d %H:%M:%S", time.gmtime()) + ' +0000'

def getTimeIsoLocal():
    return time.strftime ("%Y-%m-%d %H:%M:%S", time.localtime())

def getTimeIsoLocalAndZone():
    return time.strftime ("%Y-%m-%d %H:%M:%S %Z", time.localtime())

def extractDate(d, dtype='xx DD.MM.YYYY hh:mm:ss.xx'):
    '''
    input : xx DD.MM.YYYY hh:mm:ss.xx
    output: YYYY-MM-DD hh:mm:ss
    '''
    res = 'YYYY-MM-DD hh:mm:ss'
    if dtype == 'xx DD.MM.YYYY hh:mm:ss.xx':

        m = re.search("(\d{1,2})\.(\d{1,2})\.(\d{2,4}) (\d{2}):(\d{2}):(\d{2})", d)
        if m:
            day, month, year = m.group(1, 2, 3)
            hour, minute, second = m.group(4, 5, 6)
            res = "%s-%s-%s %s:%s:%s" % (year, month, day, hour, minute, second)
        else:
            return False
            #res = '2000-01-01 01:01:01'
    return res 

def dtNow(dtype):
    ''' generate timestamp string
    '''
    if   dtype == 10: dt = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    elif dtype == 11: dt = time.strftime("%d.%m.%Y %H:%M:%S", time.localtime())
    elif dtype == 12: dt = time.strftime("%d.%m.%Y %H:%M", time.localtime())

    elif dtype == 20: dt = time.strftime("%Y%m%d_%H%M%S", time.localtime())
    elif dtype == 21: dt = time.strftime("%Y%m%dT%H%M%S", time.localtime())

    elif dtype == 30: dt = time.strftime("%Y%m%d%H%M%S", time.localtime())

    elif dtype == 40: dt = time.strftime("%m%d", time.localtime())
    elif dtype == 41: dt = time.strftime("%w", time.localtime())
    # %w Weekday as a decimal number [0(Sunday),6]

    else:
        return False
    return dt

def getDayOfWeek(isoDateString):
    ''' return day of the week
    >>> getDayOfWeek('2008-02-22')
    'Friday'
    '''
    Weekday = ['Monday', 'Tuesday', 'Wednesday', 'Thursday',
    'Friday', 'Saturday', 'Sunday']

    # day of week (Monday = 0) of a given month/day/year
    t1 = time.strptime(isoDateString,"%Y-%m-%d")
    # year in time_struct t1 can not go below 1970 (start of epoch)!
    t2 = time.mktime(t1)
    return Weekday[(time.localtime(t2)[6])]

def getYear(cyear=2007):
    ''' prints year calendar
    '''
    calendar.prcal(cyear)
    
def getMnth(cyear=2009, cmonth=10):
    ''' print mont calendar
    >>> getMnth(cyear=1973, cmonth=10)
        October 1973
    Mo Tu We Th Fr Sa Su
     1  2  3  4  5  6  7
     8  9 10 11 12 13 14
    15 16 17 18 19 20 21
    22 23 24 25 26 27 28
    29 30 31
    '''
    calendar.prmonth(cyear, cmonth) 

def mnthSpan(ym):
    """
    >>> mnthSpan('2001-02')
    ('2001-2-1 00:00:00', '2001-2-28 23:59:59')
    """
    y, m  = int(ym[:4]), int(ym[-2:])
    d = calendar.monthrange(y, m)[1]
    #res = ( "1.%s.%s 00:00:00" % (m, y)
    #       ,"%s.%s.%s 23:59:59"  % (d, m, y))
    res = ( "%s-%s-1 00:00:00" % (y, m)
           ,"%s-%s-%s 23:59:59"  % (y, m, d))
    return res

def isWeekend(isodate):
    if len(isodate) == 10:
        ymd = string.split(isodate, '-')
        wday = datetime.date(int(ymd[0]), int(ymd[1]), int(ymd[2])).isoweekday()
    
        if wday in (6,7):
            return True
        else:
            return False
    else:
        return False

def getWeekday(inDateIso):
    ymd = string.split(inDateIso,'-')
    wday = datetime.date(int(ymd[0]), int(ymd[1]), int(ymd[2])).isoweekday()
    return wday


if __name__ == "__main__":
    import doctest
    doctest.testmod()

    print datetime.datetime.now()
    #2008-07-16 19:44:18.733000

    print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    #2008-07-16 19:44:18
    print time.strftime("%Y-%m", time.localtime())
    #2008-07

    print getTimeIsoGmt()
    print getTimeIsoLocal()
    print getTimeIsoLocalAndZone()

    print dtNow(10)
    now = date.today()
    print now

    #datetime.date(2003, 12, 2)
    print now.strftime("%m-%d-%y; %d %b %Y is a %A on the %d day of %B")
    #'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'

    # dates support calendar arithmetic
    birthday = date(1973, 10, 6)
    age = now - birthday
    print age.days
    print round(D(age.days)/365,25)

